<template>
    <el-container>
        <el-header>
            <el-button type="primary" size="small" @click="add">添加</el-button>
            <el-button type="primary" size="small" @click="editShow">编辑</el-button>
        </el-header>
        <el-container>
            <el-aside width="400px">
                <el-tree ref="tree" class="aside-tree" :data="treeData" node-key="id" accordion default-expand-all
                    highlight-current check-on-click-node :expand-on-click-node="false" @node-click="handleNodeClick">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span>
                            <el-button v-if="data.type === 'menu'" class="primarybtn-color" type="text" size="mini"
                                @click="() => add(node, data)">
                                添加下级
                            </el-button>
                            <el-button class="dangerbtn-color" type="text" size="mini" @click="() => removeNode(node, data)">
                                删除
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </el-aside>
            <el-main>
                <df-element-form v-if="formHackReset" :formConfig="formConfig" :value="formValue" ref="customForm">
                </df-element-form>

                <div v-if="edit" style="padding-left:100px">
                    <el-button type="primary" size="small" @click="saveForm">保存</el-button>
                    <el-button size="small" @click="cancelForm">取消</el-button>
                </div>
            </el-main>
        </el-container>
    </el-container>
</template>

<script>
    import {
        api
    } from '@/api/common';
    import SearchCol from '@/components/view/search_col'
    import {
        getFormConfigData
    } from '@/const/views/system/dev/menu'

    export default {
        components: {
            SearchCol
        },
        data() {
            return {
                formHackReset: true,
                checkAll: false,
                treeCheckedData: [],
                editCompanyID: '',
                edit: false,
                authTreeData: [], // 菜单树
                treeData: [], // 菜单树
                dialogAuthVisible: false, // 授权弹出框
                dialogAuthTitle: '', // 授权弹出标题
                originFormConfig: [], // 表单配置数据
                formValue: {}, // 表单值
            }
        },
        created() {
            this.getTreeData()
            this.getFormConfig()
        },
        computed: {
            formConfig: function() {
                let _formConfig = this.originFormConfig[0]

                for (let index = 0; index < _formConfig.formItemList.length; index++) {
                    const element = _formConfig.formItemList[index];
                    if (element.key === 'parent_id') {
                        this.$set(_formConfig.formItemList[index], 'options', this.treeData)
                    }
                }
                if (this.formValue.hasOwnProperty('type')) {
                    for (let index = 0; index < _formConfig.formItemList.length; index++) {
                        const element = _formConfig.formItemList[index];
                        if (element.key === 'authtype') {
                            const ruleIndex = element['rules'].findIndex(r => r.required !== undefined)
                            if (this.formValue['type'] === 'menu') {
                                ruleIndex > -1 && _formConfig.formItemList[index]['rules'].splice(ruleIndex, 1);
                            } else {
                                ruleIndex === -1 &&
                                    _formConfig.formItemList[index]['rules'].unshift({
                                        required: true,
                                        message: '必填项',
                                        trigger: 'change',
                                    });
                            }
                        }
                    }
                }

                this.$set(_formConfig, 'disabled', !this.edit)

                return _formConfig
            }
        },
        methods: {
            // 绑定弹窗子组件的关闭
            handleCloseBindDialogForm() {
                this.dialogAuthVisible = false
                this.dialogAuthTitle = ''
            },
            // 获取表单配置
            getFormConfig() {
                var _this = this

                _this.originFormConfig = getFormConfigData()
            },
            // 树
            getTreeData() {
                let _this = this
                _this.axios.post(api.getMenuListTree).then((res) => {
                    // console.log(res)
                    if (res.data.code == 10000) {
                        _this.treeData = res.data.data
                    } else {
                        _this.treeData = []
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.treeData = []
                    console.log('调用失败', err)
                })
            },
            // 点击树
            handleNodeClick(data) {
                if (this.edit === false) {
                    // console.log(data);
                    this.formValue = data
                    this.formValue['parent_id'] = data.parent_id
                    this.formHackReset = false
                    this.$nextTick(() => {
                        this.formHackReset = true
                    })
                }
            },
            cancelForm() {
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
                this.edit = false
            },
            // 编辑显示
            editShow() {
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
                this.edit = true
            },
            // 删除树节点
            removeNode(node, data) {
                // console.log(node,data);
                let _this = this,
                    params = {
                        id: data.id,
                    }
                if (!data.hasOwnProperty('children') || data.children.length <= 0) {
                    _this.$confirm('该操作会永久删除该节点, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        _this.axios.post(api.menuRmv, params).then((res) => {
                            if (res.data.code == 10000) {
                                _this.$message({
                                    showClose: false,
                                    message: res.data.message,
                                    type: 'success'
                                });
                                const parent = node.parent;
                                const children = parent.data.children || parent.data;
                                const index = children.findIndex(d => d.id === data.id);
                                children.splice(index, 1);
                            } else {
                                _this.$message({
                                    showClose: false,
                                    message: res.data.message,
                                    type: 'error'
                                })
                            }
                        }).catch(() => {
                            _this.$message({
                                showClose: false,
                                message: '调用失败',
                                type: 'error'
                            });
                        })
                    })
                } else {
                    this.$message({
                        message: '该节点下存在子节点，不允许删除',
                        type: 'warning'
                    });
                }
            },
            saveForm() {
                let _this = this,
                    url = api.menuCrd,
                    params = this.formValue
                if (this.formValue.hasOwnProperty('id') && this.formValue['id'] != '') {
                    url = api.menuEdt
                }

                _this.handleAxiosFun(url, params)
            },
            // 添加
            add(node, data) {
                // let curNode = this.$refs.tree.getCurrentNode()
                this.edit = true
                this.formValue = {}
                if (data) {
                    this.formValue['parent_id'] = data.id
                }
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
            },
            // 表格行操作列按钮点击（转发）
            rowbtnclick(func, row) {
                this[func](row)
            },
            // axios接口请求
            handleAxiosFun(url, params, _sucess_callback, _fail_callback) {
                let _this = this

                _this.axios.post(url, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'success'
                        });
                        if (_sucess_callback && typeof _sucess_callback === 'function') {
                            _sucess_callback()
                        } else {
                            _this.getTreeData();
                            _this.edit = false
                            _this.formValue = {}
                            _this.formHackReset = false
                            _this.$nextTick(() => {
                                _this.formHackReset = true
                            })
                            _this.editCompanyID = ''
                            _this.dialogAuthVisible = false
                            _this.dialogAuthTitle = ''
                        }
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                        if (_fail_callback && typeof _fail_callback === 'function') {
                            _fail_callback()
                        }
                    }
                }).catch(() => {
                    _this.$message({
                        showClose: false,
                        message: '调用失败',
                        type: 'error'
                    });
                })
            }
        }
    }
</script>

<style lang="scss">
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }

    .aside-tree {
        margin-right: 20px;
        height: 100%;
        overflow: auto;
    }
</style>
